<route lang="json5">
{
  style: {
    navigationBarTitleText: '信访服务',
    navigationBarTextStyle: 'white', //标题栏字体颜色
    navigationBarBackgroundColor: '#0063AF', //标题栏背景色(纯色)
  },
}
</route>
<template>
  <view class="petitioneSub bg-#F4F5F9 p-30rpx w-screen h-screen box-border overflow-auto">
    <wd-form ref="form" :model="model" :rules="rules">
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">信访人信息</view>
        <view class="rounded-20rpx overflow-hidden">
          <wd-input
            label="姓名"
            label-width="100px"
            prop="name"
            clearable
            v-model="model.name"
            placeholder="请输入姓名"
          />
          <wd-input
            label="身份证号"
            label-width="100px"
            prop="idCard"
            clearable
            v-model="model.idCard"
            placeholder="请输入身份证号"
          />
          <wd-input
            label="手机号码"
            label-width="100px"
            prop="phone"
            clearable
            v-model="model.phone"
            placeholder="请输入手机号码"
          />
        </view>
      </view>
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">信访人身份证</view>
        <view class="rounded-20rpx w-100% overflow-hidden flex gap-20rpx">
          <view class="flex-1 overflow-hidden box-border">
            <wd-cell title-width="0rpx" prop="idCardUrl1">
              <image
                v-if="model.idCardUrl1 == ''"
                class="w-280rpx h-150rpx"
                src="../../../static/menu/portrait.png"
                mode="scaleToFill"
                @click="chooseAndUploadImage('idCardUrl1')"
              />
              <image
                v-else
                class="w-280rpx h-150rpx"
                :src="baseurl + model.idCardUrl1"
                mode="scaleToFill"
              />
            </wd-cell>
          </view>
          <view class="flex-1 overflow-hidden box-border">
            <wd-cell class="flex-1" title-width="0rpx" prop="idCardUrl2">
              <image
                v-if="model.idCardUrl2 == ''"
                class="w-280rpx h-150rpx"
                src="../../../static/menu/emblem.png"
                mode="scaleToFill"
                @click="chooseAndUploadImage('idCardUrl2')"
              />
              <image
                v-else
                class="w-280rpx h-150rpx"
                :src="baseurl + model.idCardUrl2"
                mode="scaleToFill"
              />
            </wd-cell>
          </view>
        </view>
      </view>
      <view class="mb-20rpx">
        <wd-textarea
          label="信访内容"
          label-width="100px"
          type="textarea"
          v-model="model.content"
          :maxlength="300"
          show-word-limit
          placeholder="请输入信访内容"
          clearable
          prop="content"
        />
      </view>
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">上传相关材料（图片）（选填）：</view>
        <view class="rounded-20rpx p-20rpx box-border bg-#fff overflow-hidden">
          <wd-cell title-width="0rpx" prop="fileList">
            <wd-upload
              :file-list="model.fileList"
              multiple
              name="file"
              image-mode="aspectFill"
              :action="actions"
              @change="handleFileChange"
              @success="handleChange"
              class="bg-#fff"
            ></wd-upload>
          </wd-cell>
        </view>
      </view>
      <view class="footer">
        <wd-button class="bg-#0A4484" type="primary" size="large" @click="submitHandler" block>
          提交
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script setup lang="ts">
import { FormRules } from 'wot-design-uni/components/w-d-form/src/types'
import { postPetitionAPI } from '@/service/index/foo'
import { useUserStore } from '@/store'
import _ from 'lodash'
import { useToast } from 'wot-design-uni'
const userStore = useUserStore()
const model = reactive<{
  name: string
  idCard: string
  phone: string
  content: string
  type: number
  files: string[]
  fileList: Record<string, string>[]
  status: number
  idCardUrl1: string
  idCardUrl2: string
  businessType: string
  // roleId: number
}>({
  name: '',
  type: 1,
  idCard: '',
  idCardUrl1: '',
  idCardUrl2: '',
  phone: '',
  content: '',
  fileList: [],
  files: [],
  status: 1,
  businessType: 'xinFang',
  // roleId: userStore.userInfo.zhuanId,
})
const toast = useToast()
const form = ref()
const rules: FormRules = {
  name: [
    {
      required: true,
      message: '请输入姓名',
      pattern: /^[\u4e00-\u9fa5]+$/,

      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入姓名'))
        }
      },
    },
  ],
  idCardUrl1: [
    {
      required: true,
      message: '请选择身份证正面',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请选择身份证正面'))
        }
      },
    },
  ],
  idCardUrl2: [
    {
      required: true,
      message: '请选择身份证背面',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请选择身份证背面'))
        }
      },
    },
  ],
  content: [
    {
      required: true,
      message: '请输入信访内容',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入信访内容'))
        }
      },
    },
  ],
  idCard: [
    {
      required: true,
      message: '请输入正确的身份证号',
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\d|X|x]$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入身份证号')
        }
      },
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入正确的手机号',
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入手机号')
        }
      },
    },
  ],
  fileList: [
    {
      required: false,
      message: '请选择活动图片',
      validator: (value) => {
        if (Array.isArray(value) && value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject()
        }
      },
    },
  ],
}
const fileList = ref<any[]>([])

const baseurl = import.meta.env.VITE_SERVER_BASEURL
const actions: string = baseurl + '/app-api/infra/file/upload-id'
const action: string = baseurl + '/app-api/infra/file/upload'
onLoad((options) => {
  model.type = options.type
})
function handleChange({ file }) {
  const { data } = JSON.parse(file.response)
  model.files.push(data)
}
function handleFileChange({ fileList }) {
  console.log(fileList, 1111111111111111)
  model.fileList = fileList
}
function chooseAndUploadImage(type) {
  // 选择图片
  uni.chooseImage({
    count: 1, // 默认9，设置图片的数量
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths
      toast.loading({
        msg: '识别中...',
      })
      uni.uploadFile({
        url: '/app-api/send/IdCard', // 开发者服务器的URL
        filePath: tempFilePaths[0],
        name: 'file', // 必填，文件对应的 key
        success: (res) => {
          const { code } = JSON.parse(res.data)
          if (code != 500) {
            uni.uploadFile({
              url: '/app-api/infra/file/upload', // 开发者服务器的URL
              filePath: tempFilePaths[0],
              name: 'file', // 必填，文件对应的 key
              success: (res) => {
                const { data } = JSON.parse(res.data)
                if (type == 'idCardUrl1') {
                  model.idCardUrl1 = data
                } else {
                  model.idCardUrl2 = data
                }
                toast.close()
                toast.success({
                  msg: '识别成功',
                })
              },
              fail: (uploadFileErr) => {
                toast.close()
                toast.error({
                  msg: '识别失败，重新上传',
                })
                console.error('upload fail:', uploadFileErr)
              },
            })
          } else {
            toast.error({
              msg: '识别失败，重新上传',
            })
          }
        },
        fail: (uploadFileErr) => {
          toast.error({
            msg: '识别失败，重新上传',
          })
          console.error('upload fail:', uploadFileErr)
        },
      })
    },
    fail: (chooseImageErr) => {
      console.error('choose image fail:', chooseImageErr)
    },
  })
}
const submitHandler = _.debounce(() => {
  handleSubmit()
}, 1000)
function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        try {
          postPetitionAPI({
            ...model,
            fileList: undefined,
            files: [...model.files],
            openId: userStore.userInfo.openid,
          }).then((res) => {
            if (res.code === 0) {
              toast.success({
                msg: '操作成功',
                duration: 0,
              })
            } else {
              toast.error({
                msg: res.msg,
                duration: 0,
              })
            }

            setTimeout(() => {
              uni.navigateBack({
                delta: 2,
              })
              toast.close()
            }, 1500)
          })
        } catch (error) {
          console.log(error)
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
</script>
<style lang="scss" scoped>
::v-deep .wd-upload {
  background: #fff;
}

::v-deep .wd-cell {
  padding-left: 0rpx !important;
}

::v-deep .wd-cell__wrapper {
  padding: 10rpx !important;
}

::v-deep .wd-cell__left {
  margin-right: 5rpx !important;
}
</style>
